const lib = require('./lib')
const rq = require('inquirer')
const lodash = require('lodash')

const jp_enable = lib.getPublishPlugins().enables;
const jp_disable = lib.getPublishPlugins().disables;
let jps = lodash.concat(jp_enable, jp_disable);
jps = lodash.compact(jps)

let choiceEnable = lodash.isArray(jp_enable) ? jp_enable : [jp_enable]
let choiceDisable = lodash.isArray(jp_disable) ? jp_disable : [jp_disable]

rq.prompt([
    {
        type: "checkbox",
        name: "enableJPs",
        message: "启用状态的 JS 加载项如下，通过空格键进行勾选（被勾选的将被关闭）：",
        choices: choiceEnable[0] == undefined ? [] : lodash.map(choiceEnable, o => o.name)
    },
    {
        type: "checkbox",
        name: "disenableJPs",
        message: "关闭状态的 JS 加载项如下，通过空格键进行勾选（被勾选的将被开启）：",
        choices: choiceDisable[0] == undefined ? [] : lodash.map(choiceDisable, o => o.name)
    }
]).then(ans => {
    let a1 = ans.enableJPs;
    let a2 = ans.disenableJPs;
    if (a1.length > 0) {
        jps = lodash.map(jps, o => {
            if (a1.includes(o.name)) {
                o = lodash.assignIn(o, { enable: "false" })
            }
            return o;
        })
    }
    if (a2.length > 0) {
        jps = lodash.map(jps, o => {
            if (a2.includes(o.name)) {
                o = lodash.assignIn(o, { enable: "true" })
            }
            return o;
        })
    }
    if (a1.length > 0 || a2.length > 0) {
        // 更新 publish.xml
        let data = lib.buildXML(jps)
        data = data.replace(/^\  /g, "    ");
        lib.changePublishxml(data)
        // done
        console.log(`   文件：${lib.publishXmlPath}已经更新，下次启动 WPS 后生效。↓`)
        console.table(jps)
    } else {
        console.log(`   貌似没有做任何更改：↓`)
        console.table(jps)
    }

}).catch(e => {
    console.error(e)
})